package com.wsg.lightaccounting.Fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.wsg.lightaccounting.Activity.CashCardActivity;
import com.wsg.lightaccounting.Activity.ChoiceAccountActivity;
import com.wsg.lightaccounting.Activity.CreditCardActivity;
import com.wsg.lightaccounting.Activity.CustomzedActivity;
import com.wsg.lightaccounting.Activity.MainActivity;
import com.wsg.lightaccounting.Activity.NetworkPaymentActivity;
import com.wsg.lightaccounting.Adapter.IconAccountAdapter;
import com.wsg.lightaccounting.Model.Account;
import com.wsg.lightaccounting.Model.AccountManager;
import com.wsg.lightaccounting.Model.CreditCard;
import com.wsg.lightaccounting.PopupWindow.CashupdatePopupWindow;
import com.wsg.lightaccounting.R;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link WalletFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link WalletFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WalletFragment extends Fragment {
    private ListView listView;
    private TextView balance;
    private IconAccountAdapter iconAccountAdapter;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(),ChoiceAccountActivity.class);
            getActivity().startActivity(intent);
        }
    };
    public static String UPDATE_WALLET_FRAGMENT = "update wallet fragmenr ui";
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UPDATE_WALLET_FRAGMENT)){
               updateUI();
            }
        }
    };

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public WalletFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment WalletFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static WalletFragment newInstance(String param1, String param2) {
        WalletFragment fragment = new WalletFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UPDATE_WALLET_FRAGMENT);
        getActivity().registerReceiver(broadcastReceiver,intentFilter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wallet, container, false);
        initView(view);
        return view;
    }
    private void initView(View view){
        listView = (ListView) view.findViewById(R.id.wallet_list);
        balance = (TextView) view.findViewById(R.id.balance_wallet);
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                deletAccount(AccountManager.accounts.get(position));
                updateUI();
                return false;
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (id == 0L){
                    updateCashBalance();
                }
                else {
                goEditActivity(AccountManager.accounts.get(position).getType(),AccountManager.accounts.get(position).getId());}
            }
        });
        setAddView();
        iconAccountAdapter = new IconAccountAdapter(getActivity());
        listView.setAdapter(iconAccountAdapter);
    }

    private void setAddView(){
        View addView = getActivity().getLayoutInflater().inflate(R.layout.wallet_layout,null);
        ImageView imageView = (ImageView) addView.findViewById(R.id.wallet_icon);
        addView.setOnClickListener(onClickListener);
        listView.addFooterView(addView);
    }
    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        updateUI();
    }
    private void deletAccount(final Account account){
        if (account.getType() == 0){
            new AlertDialog.Builder(getActivity()).setTitle("系统提示").setMessage("现金不能删除！").show();
        }
        else {
            new AlertDialog.Builder(getActivity()).setTitle("系统提示").setMessage("删除账户会让与账户有关的数据全部清空，是否删除！")
                    .setPositiveButton("确定",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                           AccountManager.getAccountManager(getActivity()).deleteAccount(account);
                            MainActivity.updateAllUI(getActivity());
                        }
                    }).setNegativeButton("返回",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        }
    }
    private void updateUI(){
        balance.setText(String.valueOf(AccountManager.getSum()));
        iconAccountAdapter.notifyDataSetChanged();
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void updateCashBalance(){
        CashupdatePopupWindow cashupdatePopupWindow = new CashupdatePopupWindow(getActivity(),this.getView().getWidth(),
                this.getView().findViewById(R.id.size).getHeight()*3);
        cashupdatePopupWindow.showAtLocation(this.getView(), Gravity.BOTTOM,0,0);
    }
    private void goEditActivity(int type,long id){
        Bundle bundle=new Bundle();
        bundle.putBoolean("isEdit",true );

        switch (type){
            case 1:
                Intent intent1 = new Intent(getActivity(), NetworkPaymentActivity.class);
                bundle.putString("type",AccountManager.findNetworkPayment(id).getInformation());
                bundle.putString("name",AccountManager.findNetworkPayment(id).getName());
                bundle.putLong("id",AccountManager.findNetworkPayment(id).getAccount_id());
                intent1.putExtras(bundle);
                getActivity().startActivity(intent1);
                break;
            case 2:
                Intent intent2 = new Intent(getActivity(), CashCardActivity.class);
                bundle.putString("bank_name",AccountManager.findCashCardById(id).getBank());
                bundle.putString("card_id",AccountManager.findCashCardById(id).getCard_id());
                bundle.putString("name",AccountManager.findCashCardById(id).getName());
                bundle.putLong("id",AccountManager.findCashCardById(id).getAccount_id());
                intent2.putExtras(bundle);
                getActivity().startActivity(intent2);
                break;
            case 3:
                Intent intent3 = new Intent(getActivity(), CreditCardActivity.class);
                bundle.putString("bank_name",AccountManager.findCreditCardById(id).getBank());
                bundle.putString("card_id",AccountManager.findCreditCardById(id).getCard_id());
                bundle.putString("name",AccountManager.findCreditCardById(id).getName());
                bundle.putFloat("credit",AccountManager.findCreditCardById(id).getLimit());
                bundle.putLong("id",AccountManager.findCreditCardById(id).getAccount_id());
                intent3.putExtras(bundle);
                getActivity().startActivity(intent3);
                break;
            case 4:
                Intent intent4 = new Intent(getActivity(), CustomzedActivity.class);
                bundle.putString("name",AccountManager.findCustomized(id).getName());
                bundle.putFloat("balance",AccountManager.findAccountById(id).getBalance());
                bundle.putFloat("color",AccountManager.findAccountById(id).getColor());
                bundle.putLong("id",AccountManager.findCustomized(id).getAccount_id());
                intent4.putExtras(bundle);
                getActivity().startActivity(intent4);
                break;
            default:
                break;
        }
    }
}
